package cn.fl.splrate.utils;

import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.splrate.vo.SplRateImportTempVO;
import cn.fl.splrate.vo.SplRateRelInfoVO;
import cn.lb.framework.poi.excel.ExcelImportUtil;
import cn.lb.framework.poi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;

import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.framework.enums.SplGrpRelInfoSrcEnum;
import fl.spl.facade.framework.enums.common.MagicNumReplaceEnum;
import fl.spl.facade.lnkcomp.constant.LnkCompFlowConstant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Function: 经销商/挂靠公司评级导入
 * Created by Administrator on 2019-10-08 17:03:38.
 */
public class ImportSplRateList {

    private static final Logger logger = LoggerFactory.getLogger(ImportSplRateList.class);

    /**
     * 经销商/挂靠公司评级导入
     *
     * @param filePath 源文件路径
     * @param dataTyp LNK(挂靠公司),SPL(供应商)
     * @return
     */
    public static Map<String, List<SplRateRelInfoVO>> importSplRateRelInfoVOXls(String rootPath, String filePath, Map<String, String> starLvlCdNmMap, Long parseFileRecId,String dataTyp) {
        String methodNm = "importSplRateRelInfoVOXls";
        boolean flag = true ;
        if(LnkCompFlowConstant.FLOW_S_H_LNK.equals(dataTyp)){
        	flag = false ;
        }
        logger.info("导入经销商/挂靠公司评级文件路径=" + filePath);
        ImportParams params = new ImportParams();
        params.setTitleRows(BaseConstant.IS_YESNO_NO);//标题占用行数
        params.setHeadRows(BaseConstant.IS_YESNO_YES);//表头占用行数
        params.setNeedSave(false);//是否保存文件
        Map<String, List<SplRateRelInfoVO>> isSuccessSplRateRelInfosMap = null;
        List<SplRateImportTempVO> list = null;
        String errMsg = null;
        if (!filePath.contains("http")) {
            File file = new File(PropertiesCacheUtils.getProperty(rootPath) + filePath);
            if (file.exists()) {
                list = ExcelImportUtil.importExcel(file, SplRateImportTempVO.class, params);
            }
        } else {
            InputStream in = null;
            URLConnection connection = null;
            try {
                URL url = new URL(filePath);
                connection = url.openConnection();//打开连接 获得URLConnection类的对象
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(60000);
                in = connection.getInputStream();
                list = ExcelImportUtil.importExcel(in, SplRateImportTempVO.class, params);
            } catch (IOException e) {
                BaseLogUtils.newServiceLogger("导入经销商/挂靠公司评级读取上传文件出错")
	    			.setLogOperType(LogOperEnum.REQ)
	    			.setSysCd(SplSystemConstant.SPL_SYS_CD)
	    			.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
	    			.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
	    			.setThrowable(e)
	    			.setWarning(false)
	    			.warn(LogExceptionEnum.API_CODE_0102);
            } catch (Exception e) {
                BaseLogUtils.newServiceLogger("导入经销商/挂靠公司评级读取上传文件出错")
	    			.setLogOperType(LogOperEnum.REQ)
	    			.setSysCd(SplSystemConstant.SPL_SYS_CD)
	    			.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
	    			.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
	    			.setThrowable(e)
	    			.setWarning(false)
	    			.error(LogExceptionEnum.API_CODE_0102);
            } finally {
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        BaseLogUtils.newServiceLogger("导入经销商/挂靠公司评级读取上传文件出错")
	    	    			.setLogOperType(LogOperEnum.REQ)
	    	    			.setSysCd(SplSystemConstant.SPL_SYS_CD)
	    	    			.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
	    	    			.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
	    	    			.setThrowable(e)
	    	    			.setWarning(false)
	    	    			.error(LogExceptionEnum.API_CODE_0102);
                    }
                }
            }
        }
        //经销商/挂靠公司评分信息list
        List<SplRateRelInfoVO> splRateRelInfoVOList = null;

        if (CollectionUtils.isNotEmpty(list)) {
            isSuccessSplRateRelInfosMap = new HashMap<>();
            splRateRelInfoVOList = new ArrayList<>(list.size());
            BaseLogUtils.newServiceLogger("导入经销商/挂靠公司评级")
				.setLogOperType(LogOperEnum.REQ)
				.setSysCd(SplSystemConstant.SPL_SYS_CD)
				.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
				.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
				.setKeys("filePath",filePath,"记录数",""+list.size())
				.setWarning(false)
				.info();
            StringBuffer parseFailedCause = null;
            SplRateRelInfoVO splRateRelInfoVO = null;
            Map<String, String> starNmAndLvlCdMap = null;
            if (CollectionUtils.isMapNotEmpty(starLvlCdNmMap)) {
                starNmAndLvlCdMap = new HashMap<>(starLvlCdNmMap.size());
                for (Map.Entry<String, String> entry : starLvlCdNmMap.entrySet()) {
                    starNmAndLvlCdMap.put(entry.getValue(), entry.getKey());
                }
            }
            boolean isSuccess = true;
            for (SplRateImportTempVO vo : list) {
                BaseLogUtils.newServiceLogger("导入经销商/挂靠公司评级")
	    			.setLogOperType(LogOperEnum.REQ)
	    			.setSysCd(SplSystemConstant.SPL_SYS_CD)
	    			.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
	    			.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
	    			.setKeys("filePath",filePath,"vo",JSON.toJSONString(vo))
	    			.setWarning(false)
	    			.info();
                errMsg = null;
                splRateRelInfoVO = new SplRateRelInfoVO();
                if(LnkCompFlowConstant.FLOW_S_H_LNK.equals(dataTyp)){
                	if (StringUtils.isNotEmpty(vo.getLnkId()) && checkFildIsNum(vo.getLnkId())) {
                		splRateRelInfoVO.setDataId(Long.valueOf(vo.getLnkId()));
                	}else if(StringUtils.isNotEmpty(vo.getDataId()) && checkFildIsNum(vo.getDataId())){
                		errMsg = "模板有误！";
                		parseFailedCause = new StringBuffer();
                		parseFailedCause.append(errMsg);
                	}else {
                		errMsg = "导入挂靠公司ID为空或非数字！当前值：" + vo.getLnkId();
                		parseFailedCause = new StringBuffer();
                		parseFailedCause.append(errMsg);
                	}
                	if (StringUtils.isNotEmpty(vo.getLnkNm())) {
                		splRateRelInfoVO.setDataNm(vo.getLnkNm());
                	} else {
                		errMsg = "导入挂靠公司名称为空！当前值：" + vo.getLnkNm();
                		if (null == parseFailedCause) {
                			parseFailedCause = new StringBuffer();
                			parseFailedCause.append(errMsg);
                		} else {
                			parseFailedCause.append(";").append(errMsg);
                		}
                	}
                    if(StringUtils.isNotEmpty(vo.getControlRate())){
                        splRateRelInfoVO.setControlRate(Double.valueOf(vo.getControlRate()));
                    }else{
                        errMsg = "挂靠公司控制力分数为空！当前值：" + vo.getControlRate();
                        if (null == parseFailedCause) {
                            parseFailedCause = new StringBuffer();
                            parseFailedCause.append(errMsg);
                        } else {
                            parseFailedCause.append(";").append(errMsg);
                        }
                    }
                }else{
                	if (StringUtils.isNotEmpty(vo.getDataId()) && checkFildIsNum(vo.getDataId())) {
                		splRateRelInfoVO.setDataId(Long.valueOf(vo.getDataId()));
                	}else if(StringUtils.isNotEmpty(vo.getLnkId()) && checkFildIsNum(vo.getLnkId())) {
                		errMsg = "模板有误！";
                		parseFailedCause = new StringBuffer();
                		parseFailedCause.append(errMsg);
                	} else {
                		errMsg = "导入经销商ID为空或非数字！当前值：" + vo.getDataId();
                		parseFailedCause = new StringBuffer();
                		parseFailedCause.append(errMsg);
                	}
                	if (StringUtils.isNotEmpty(vo.getDataNm())) {
                		splRateRelInfoVO.setDataNm(vo.getDataNm());
                	} else {
                		errMsg = "导入经销商名称为空！当前值：" + vo.getDataNm();
                		if (null == parseFailedCause) {
                			parseFailedCause = new StringBuffer();
                			parseFailedCause.append(errMsg);
                		} else {
                			parseFailedCause.append(";").append(errMsg);
                		}
                	}
                }
                if (StringUtils.isNotEmpty(vo.getRateLvl())) {
                    splRateRelInfoVO.setRateLvl(vo.getRateLvl());
                }
                if (StringUtils.isNotEmpty(vo.getRateScore()) && checkFildIsNum(vo.getRateScore())) {
                    String[] splitRateScore = vo.getRateScore().split("\\.");
                    BaseLogUtils.newServiceLogger("导入经销商/挂靠公司评级")
		    			.setLogOperType(LogOperEnum.REQ)
		    			.setSysCd(SplSystemConstant.SPL_SYS_CD)
		    			.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
		    			.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
		    			.setKeys("filePath",filePath,"splitRateScore",JSON.toJSONString(splitRateScore))
		    			.setWarning(false)
		    			.info();
                    if (Integer.parseInt(splitRateScore[0]) > 10) {
                        errMsg = "导入经销商/挂靠公司评分超过最大值10！当前值：" + vo.getRateScore();
                        if (null == parseFailedCause) {
                            parseFailedCause = new StringBuffer();
                            parseFailedCause.append(errMsg);
                        } else {
                            parseFailedCause.append(";").append(errMsg);
                        }
                    } else {
                        if (splitRateScore.length > 2) {
                            splRateRelInfoVO.setRateScore(0.00);
                            errMsg = "导入经销商/挂靠公司评分数字错误！当前值：" + vo.getRateScore();
                            if (null == parseFailedCause) {
                                parseFailedCause = new StringBuffer();
                                parseFailedCause.append(errMsg);
                            } else {
                                parseFailedCause.append(";").append(errMsg);
                            }
                        } else {
                            DecimalFormat decimalFormat = new DecimalFormat("##.##");
                            splRateRelInfoVO.setRateScore(Double.valueOf(decimalFormat.format(new BigDecimal(vo.getRateScore()))));
                        }
                    }
                } else {
                    errMsg = "导入经销商/挂靠公司评分为空或非数字，请检查后上传！当前值：" + vo.getRateScore();
                    if (null == parseFailedCause) {
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    } else {
                        parseFailedCause.append(";").append(errMsg);
                    }
                }
                if (StringUtils.isNotEmpty(vo.getStarLevel())) {
                    if (CollectionUtils.isMapEmpty(starNmAndLvlCdMap)) {
                        throw new BaseException(BaseExceptionConstant.COMMON_0001, "因经销商/挂靠公司星级数据字典异常导致解析失败，请联系管理员！");
                    } else {
                        if (starNmAndLvlCdMap.containsKey(String.valueOf(vo.getStarLevel()))) {
                            splRateRelInfoVO.setStarLevel(Long.valueOf(starNmAndLvlCdMap.get(String.valueOf(vo.getStarLevel()))));
                        } else {
                            errMsg = "导入经销商/挂靠公司星级与数据字典匹配失败！当前值：" + vo.getStarLevel();
                            if (null == parseFailedCause) {
                                parseFailedCause = new StringBuffer();
                                parseFailedCause.append(errMsg);
                            } else {
                                parseFailedCause.append(";").append(errMsg);
                            }
                        }
                    }
                } else {
                    errMsg = "导入经销商/挂靠公司星级为空！当前值：" + vo.getRateScore();
                    if (null == parseFailedCause) {
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    } else {
                        parseFailedCause.append(";").append(errMsg);
                    }
                }
                if (null != parseFailedCause && parseFailedCause.length() > BaseConstant.IS_YESNO_NO) {
                    splRateRelInfoVO.setParseFailedCause(parseFailedCause.toString());
                    parseFailedCause.setLength(BaseConstant.IS_YESNO_NO);
                }
                splRateRelInfoVO.setDataSource(SplGrpRelInfoSrcEnum.SRC_IMPORT.getRelInfoSrc());
                splRateRelInfoVO.setIsDel(BaseConstant.IS_YESNO_NO);
                if (null != errMsg) {
                    if (isSuccess) {
                        isSuccess = false;
                    }
                    splRateRelInfoVO.setIsSuccess(BaseConstant.IS_YESNO_NO);
                } else {
                    splRateRelInfoVO.setIsSuccess(BaseConstant.IS_YESNO_YES);
                }
                splRateRelInfoVO.setIsValid(BaseConstant.IS_YESNO_YES);
                splRateRelInfoVO.setIsNew(MagicNumReplaceEnum.REP_NON_YESNO_VAL.getVal());
                splRateRelInfoVO.setParseFileRecId(parseFileRecId);
                splRateRelInfoVO.setCrtTm(new Date());
                splRateRelInfoVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                splRateRelInfoVOList.add(splRateRelInfoVO);
            }
            if (isSuccess) {
                isSuccessSplRateRelInfosMap.put(BaseConstant.IS_YESNO_YES_STR, splRateRelInfoVOList);
            } else {
                isSuccessSplRateRelInfosMap.put(BaseConstant.IS_YESNO_NO_STR, splRateRelInfoVOList);
            }
        } else {
            BaseLogUtils.newServiceLogger("导入经销商/挂靠公司评级")
				.setLogOperType(LogOperEnum.REQ)
				.setSysCd(SplSystemConstant.SPL_SYS_CD)
				.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
				.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
				.setKeys("filePath",filePath,"记录数","0")
				.setWarning(false)
				.info();
        }
        return isSuccessSplRateRelInfosMap;
    }


    // 校验数字
    public static boolean checkFildIsNum(String field) throws BaseException {
        Pattern pattern = Pattern.compile("^(-|0|[1-9]+[0-9]*)(\\.[0]{1}\\d*|\\.[1-9]\\d*)?");
        Matcher isNum = pattern.matcher(field);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}
